package com.hyjx.framework.common;

import com.hyjx.framework.common.util.DataGrideUtil;
import com.hyjx.framework.common.util.ExcelExportUtil;
import com.hyjx.framework.component.codetable.CodeTableManager;
import com.hyjx.framework.component.excel.ExcelImportResult;
import com.hyjx.framework.component.excel.ImportUtil;
import com.hyjx.framework.service.CaptchaService;
import com.hyjx.framework.service.ConfigManager;
import com.hyjx.framework.service.RightManager;
import com.hyjx.framework.service.SessionManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.patchca.service.Captcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公共组件控制器
 *
 * @author Kingt
 */
@Controller
@RequestMapping("/common")
public class CommonController {
    /**
     * 跳转到预览页面，上传到服务器端之后预览
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoPreView", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView gotoPreView(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/common/uploadfile");
        mav.addObject("vchr_domain",
                request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain"));
        mav.addObject("vchr_entityid",
                request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid"));
        mav.addObject("fileType", request.getParameter("fileType") == null ? "" : request.getParameter("fileType"));
        return mav;
    }
    
    /**
     * 跳转到上传图片页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoUploadImage", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView gotoUploadImage(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/common/uploadImage");
        mav.addObject("vchr_domain",
                request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain"));
        mav.addObject("vchr_entityid",
                request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid"));
        mav.addObject("fileType", request.getParameter("fileType") == null ? "" : request.getParameter("fileType"));
        return mav;
    }
    
    /**
     * 导出Excel的公共方法
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/doExcelExport")
    public void doExcelExport(HttpServletRequest request, HttpServletResponse response) {
        String param = request.getParameter("paramdata");
        String data = request.getParameter("data");
        
        JSONArray resultArray = null;
        if (data == null || "".equals(data)) {
            resultArray = new JSONArray();
        } else {
            if (data.startsWith("\"")) {
                data = data.replaceAll("\\\\\"", "\"");
                data = data.substring(1, data.length() - 1);
            }
            JSONObject jobj = JSONObject.fromObject(data);
            resultArray = jobj.getJSONArray("rows");
        }
        
        JSONObject paramJson = JSONObject.fromObject(param);
        JSONArray columns = paramJson.getJSONArray("columns");
        JSONObject exportDataInfo = paramJson.getJSONObject("exportDataInfo");
        columns = columns.getJSONArray(0);
        
        try {
            ExcelExportUtil.exportExcel(columns, resultArray, exportDataInfo, response);
        } catch (Exception e) {
        }
    }
    
    /**
     * 跳转到导入excel数据页面
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoImport", method = RequestMethod.GET)
    public String gotoImport(HttpServletRequest request) {
        request.setAttribute("en_module_name", request.getParameter("en_module_name"));
        return "/framework/common/importexcel";
    }
    
    /**
     * 执行导入数据
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/doImport", produces = "application/json; charset=utf-8", method = RequestMethod.POST)
    @ResponseBody
    public String doImport(MultipartHttpServletRequest request) {
        String result = null;
        try {
            String enModuleName = request.getParameter("en_module_name");
            ImportUtil util = ImportUtil.getInstance(request, enModuleName);
            ExcelImportResult els = util.doImport();
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("erros", els.getError());
            resultMap.put("total", els.getTotal());
            resultMap.put("succs", els.getSucc());
            result = JSONObject.fromObject(resultMap).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 下载文件
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/downLoad", method = {RequestMethod.GET, RequestMethod.POST})
    public void getErrorData(HttpServletRequest request, HttpServletResponse response) {
        
        try {
            String enModuleName = request.getParameter("en_module_name");
            ImportUtil util = ImportUtil.getInstance(request, enModuleName);
            util.getErrorDate(response);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
    
    /**
     * 显示错误信息
     *
     * @param request
     * @return
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping(value = "/showErrorMsg", produces = "application/json; charset=utf-8", method = {RequestMethod.GET,
            RequestMethod.POST})
    @ResponseBody
    public String showErrorMsg(HttpServletRequest request) {
        String result = null;
        try {
            List errMsg = (List) SessionManager.get("errMsg");
            List<Map<String, String>> errorMsg = new ArrayList<Map<String, String>>();
            for (Object obj : errMsg) {
                Map<String, String> map = new HashMap<String, String>();
                map.put("errorMsg", obj.toString());
                errorMsg.add(map);
            }
            result = DataGrideUtil.getDataGridJsonByList(errorMsg);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
    
    /**
     * 附件管理
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoAtt")
    public ModelAndView gotoAtt(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/common/uploadatt");
        mav.addObject("vchr_domain",
                request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain"));
        mav.addObject("vchr_entityid",
                request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid"));
        mav.addObject("fileType", request.getParameter("fileType") == null ? "" : request.getParameter("fileType"));
        return mav;
    }
    
    /**
     * 跳转到上传视频功能
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/gotoAttVideo")
    public ModelAndView gotoAttVideo(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("/framework/upload/videoatt");
        return mav;
    }
    
    /**
     * 刷新缓存
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/doRefreshCache")
    @ResponseBody
    public String doRefreshCache(HttpServletRequest request, HttpServletResponse response) {
        Long startTime = System.currentTimeMillis();
        RightManager.init();
        ConfigManager.init();
        CodeTableManager.init();
        Long endTime = System.currentTimeMillis();
        
        return "Success! Processed " + String.valueOf(endTime - startTime) + " milliseconds";
    }
    
    /**
     * 取验证码
     */
    @RequestMapping(value = "/getValidationCode")
    @ResponseBody
    public String getValidationCode() {
        String validationCode = (String) SessionManager.get(Constants.VALIDATIONCODE);
        return validationCode;
    }
    
    @RequestMapping(value = "/getValidationCodeImage")
    public void getValidationCodeImage(HttpServletResponse response)
            throws IOException {
        response.setContentType("image/png");
        response.setHeader("cache", "no-cache");
        OutputStream outputStream = response.getOutputStream();
        Captcha captcha = CaptchaService.getCaptcha();
        String validationCode = captcha.getChallenge();
        SessionManager.set(Constants.VALIDATIONCODE, validationCode);
        
        BufferedImage bufferedImage = captcha.getImage();
        ImageIO.write(bufferedImage, "png", outputStream);
        outputStream.flush();
        outputStream.close();
    }
    
    /**
     * 头像裁剪
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/imagecrop", method = {RequestMethod.GET, RequestMethod.POST})
    @ResponseBody
    public ModelAndView imagecrop(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("framework/common/imagecrop");
        mav.addObject("vchr_domain", request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain"));
        mav.addObject("vchr_entityid", request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid"));
        mav.addObject("fileType", request.getParameter("fileType") == null ? "" : request.getParameter("fileType"));
        
        return mav;
    }
    
    /**
     * 附件预览
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/attview")
    @ResponseBody
    public ModelAndView attview(HttpServletRequest request) {
        ModelAndView mav = new ModelAndView("framework/common/attview");
        mav.addObject("viewType", request.getParameter("viewType") == null ? "" : request.getParameter("viewType"));
        mav.addObject("id", request.getParameter("id") == null ? "" : request.getParameter("id"));
        mav.addObject("vchr_domain", request.getParameter("vchr_domain") == null ? "" : request.getParameter("vchr_domain"));
        mav.addObject("vchr_entityid", request.getParameter("vchr_entityid") == null ? "" : request.getParameter("vchr_entityid"));
        return mav;
    }
}